from app.libs.error_code import  Success
from app.libs.redprint import Redprint

from flask import jsonify,request

from app.libs.token_auth import auth
from app.models.mock import Mock
from app.validators.case import IdFrom
from app.validators.mock import MockForm,SelectMockForm,UpdateMockForm


api = Redprint('mock')

@api.route('/mock_test', methods=['POST'])
@auth.login_required
def mock_test():
    request_data=request.json
    #转字符格式，去除空格
    request_data="{}".format(request_data)
    request_data=request_data.replace(" ", "")

    result=Mock.query.filter(Mock.request_data==request_data).first()
    #去掉字符串变为字典要使用eval()方法
    result=eval(result.return_data)

    return jsonify(result)

@api.route('/create_mock', methods=['POST'])
@auth.login_required
def create_case():
    form =  MockForm().validate_for_api()
    Mock.add_mock(form.function_name.data,form.request_data.data,form.return_data.data)
    return Success()

@api.route('/update_mock', methods=['POST'])
@auth.login_required
def update_case():
    form = UpdateMockForm().validate_for_api()
    mock = Mock.query.get(form.id.data)
    print(mock)
    Mock.update_mock(mock,form.function_name.data,form.request_data.data,form.return_data.data)
    return Success()

@api.route('/del_mock', methods=['POST'])
@auth.login_required
def del_case():
    form = IdFrom().validate_for_api()
    mock = Mock.query.get(form.id.data)
    Mock.del_mock(mock)
    return Success()

@api.route('/examine_mock', methods=['POST'])
@auth.login_required
def examine_case():
    form = SelectMockForm().validate_for_api()
    function_name=form.function_name.data
    if function_name:
        mocks=Mock.query.filter(Mock.function_name==form.function_name.data,Mock.del_status==1)
    else:
        mocks=Mock.query.filter(Mock.del_status==1)
    mock=[mock for mock in mocks]
    return jsonify(mock)